<?php
/**
-------------------------
GNU GPL COPYRIGHT NOTICES
-------------------------
This file is part of FlexicaCMS.

FlexicaCMS is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

FlexicaCMS is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with FlexicaCMS.  If not, see <http://www.gnu.org/licenses/>.*/

/**
 * $Id$
 *
 * @author FlexicaCMS team <contact@flexicacms.com>
 * @link http://www.flexicacms.com/
 * @copyright Copyright &copy; 2009-2010 Gia Han Online Solutions Ltd.
 * @license http://www.flexicacms.com/license.html
 */
 
class FDom extends DOMDocument
{
    // catch the error message when load XML string
    protected $errMsg;
    
    public function getError(){
        return $this->errMsg;
    }
    
    /**
    * Load XML string into document, allow that XML string to have common
    * HTML entities such as nbsp, copy, reg,...
    * 
    * @param mixed $rootName
    */
    public function loadXMLwithEntities($xml, $rootName = 'root') {
        $entities = array('nbsp','iexcl','iexcl','pound','curren','yen',
        'brvbar','sect','uml','copy','ordf','laquo','not','shy','reg','macr',
        'deg','plusmn','sup2','sup3','acute','micro','para','middot','cedil',
        'sup1','ordm','raquo','frac14','frac12','frac34','iquest');
        
        $entitiesString = '';
        $i = 160;
        foreach($entities as $ent){
            $entitiesString .= '<!ENTITY '.$ent.' "&#'.$i.';">';
            $i++;
        }
        $entitiesString .= '<!ENTITY times "&#215;"><!ENTITY divide "&#247;">';
        $doctype = "<!DOCTYPE {$rootName} [{$entitiesString}]>";
        
        if (substr($xml,1,strlen($rootName)) != $rootName)
            $xml = $doctype."<{$rootName}>".$xml."</{$rootName}>";
        else
            $xml = $doctype.$xml;
        
        set_error_handler(array($this, 'handleXmlError'));
        parent::loadXML($xml);
        restore_error_handler();
        if (!empty($this->errMsg)){
            return $this;
        }

        return $this;
    }
    
    public function handleXmlError($errno, $errstr, $errfile, $errline)
    {
        $this->errMsg = $errstr;
//        restore_error_handler();
//        if ($errno==E_WARNING && (substr_count($errstr,"DOMDocument::loadXML()")>0))
//        {
//            throw new DOMException($errstr);
//        }
//        else
//            return false;
    }    
}
?>
